package lesson04.作业.作业02;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 面试题： 写一个固定容量同步容器，拥有put和get方法，以及getCount方法
 * 能够支持2个生产者线程以及10个消费者线程的阻塞调用
 */
public class ThreadDome<T> {

    private final LinkedList<T> lists = new LinkedList<>();
    private final  int MAX = 10;
    private int count = 0;

    public synchronized void put(T t)  {
        while (lists.size() == MAX){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        lists.add(t);
        ++count;
        System.out.println(t);
        this.notify();
    }

    public synchronized T get() {
        T t = null;
        while (lists.size() == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        t = lists.removeFirst();
        count--;
        System.out.println("        "+Thread.currentThread().getName() + " - " + t);
        this.notify();
        return  t;
    }
    public Integer getCount(){
        return lists.size();
    }

    public static void main(String[] args) throws Exception {

        ThreadDome<String> dome = new ThreadDome<>();
        // 生产者
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {for (int k = 0; k < 25; k++) {
                dome.put(Thread.currentThread().getName()+"& "+ k); }}, "P-" + i).start();
                //dome.put("P "+ k); }}, "P-" + i).start();
        }
        //TimeUnit.SECONDS.sleep(2);
        // 消费者
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {for (int k = 0; k < 5; k++) { dome.get(); } }, "C->" + i).start();
        }

    }
}
